package com.example.simple_file_chooser;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.AdapterView;
import android.widget.TextView;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.RequiresApi;

/***
 * 弹框封装类
 * @author Administrator
 *
 */
public class DialogUtil extends AndroidInstance {


    private int bgcolor = -1;

    public DialogUtil setBgcolor(int bgcolor) {
        this.bgcolor = bgcolor;
        return this;
    }

    public DialogUtil() {
    }

    public static final int Neutral = 1;
    public static final int BOTN = 2;
    public static final int Three = 3;
    public static final int NONE = 4;

    public String[] arrays;

    public int layoutid;
    public int layoutitemid;

    public DialogUtil setArrays(String... arrays) {
        this.arrays = arrays;
        return this;
    }

    public DialogUtil setLayoutid(int layoutid) {
        this.layoutid = layoutid;
        return this;
    }

    public String title;

    public DialogUtil setTitle(String title) {
        this.title = title;
        return this;
    }

    public DialogUtil setLayoutitemid(int layoutitemid) {
        this.layoutitemid = layoutitemid;
        return this;
    }

    public AdapterView.OnItemClickListener onItemClickListener;

    public DialogUtil setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
        return this;
    }

    int buttonstyle;

    public DialogUtil setButtonstyle(int buttonstyle) {
        this.buttonstyle = buttonstyle;
        return this;
    }

    private static AlertDialog dialog;
    private static Dialog currentDialog;


    public static AlertDialog getCurrentDialog() {
        if (dialog != null && !dialog.isShowing()) {
            dialog.dismiss();
            dialog.cancel();
            dialog = null;
        }
        return dialog;
    }


    public static void cancelDialog() {
        Dialog dialog = getCurrentDialog();
        if (dialog != null) {
            dialog.dismiss();
            dialog.cancel();
            dialog = null;
        }
    }

    public static Dialog showDialog(String title, List<String> liststring, Context ctx, AdapterView.OnItemClickListener onitemclicklistener, int str_r_type_attr) {
        return showDialog(ctx, title, android.R.color.darker_gray, liststring, onitemclicklistener, str_r_type_attr, R.layout.auto_string_item);
    }


    public static Dialog showDialog(String title, View view, int linecolor, List<String> liststring, AdapterView.OnItemClickListener onitemclicklistener, int str_r_type_attr) {
        return showDialog(view.getContext(), title, linecolor, liststring, onitemclicklistener, str_r_type_attr, R.layout.auto_string_item);
    }

    @SuppressLint("NewApi")
    public static Dialog showDialog(Context context, String title, int linecolor, List<String> liststring, AdapterView.OnItemClickListener onitemclicklistener, int str_r_type_attr, int item_str_r_type_attr) {
        return showDialog(R.color.theme_color, context, title, linecolor, liststring, onitemclicklistener, str_r_type_attr, item_str_r_type_attr);
    }


    DialogUtil.DialogInfo du;
    AlertDialog.Builder alertbuilder;

    public AlertDialog.Builder getBuilder() {
        if (dialog != null && dialog.isShowing()) {
            DialogUtil.cancelDialog();
        }
        alertbuilder = DialogUtil.getNeutralDialogBuilder(du, true);
        return alertbuilder;
    }

    public Dialog get() {
        dialog = getBuilder().create();
        setCurrentDialog(dialog);
        return dialog;
    }

    public Dialog show() {
        dialog = getBuilder().show();
        if (Build.VERSION.SDK_INT == 28) {
            api28_9_dialog_key_problem();
        }
        setCurrentDialog(dialog);
        return dialog;
    }

    public DialogUtil addButton(int pos, String txt, DialogClicker clicker) {
        switch (pos) {
            case 0:
                du.positiveButtonText = txt;
                du.positiveButtonClickListener = clicker;
                break;

            case 1:
                du.neutralButtonText = txt;
                du.neutralButtonClickListener = clicker;
                break;
            case 2:
                du.negativeButtonText = txt;
                du.negativeButtonClickListener = clicker;
                break;
        }
        return this;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public DialogUtil addFrame(CharSequence title, int color) {
        View header = du.view.findViewById(R.id.string);
        if (header != null && ((TextView) header.findViewById(R.id.name)) != null) {
            ((TextView) header.findViewById(R.id.name)).setTextColor(du.aty.getColor(android.R.color.white));
            if (color != -1) {
                header.setBackgroundColor(color);
            }

            if (!TextUtils.isEmpty(title)) {
                ((TextView) header.findViewById(R.id.name)).setText(title);
            }
        }

        return this;
    }

    public static DialogUtil with(Context ctx) {
        DialogUtil dialogUtil = new DialogUtil(ctx);
        return dialogUtil;
    }

    public DialogUtil(Context ctx) {
        du = new DialogUtil.DialogInfo(ctx);
        du.aty = ctx;
    }

    public DialogUtil addView(final View view) {

        du.view = view;
        return this;
    }

    public DialogUtil addItemClicker(AdapterView.OnItemClickListener onitemclicklistener) {
        ((AdapterView) du.view.findViewById(R.id.listview)).setOnItemClickListener(onitemclicklistener);
        return this;
    }

    @SuppressLint("NewApi")
    public static Dialog showDialog(int thmeecolor, Context context, String title, int linecolor, List<String> liststring, AdapterView.OnItemClickListener onitemclicklistener, int str_r_type_attr, int item_str_r_type_attr) {
        return showDialog(Neutral, thmeecolor, context, title, linecolor, liststring, onitemclicklistener, str_r_type_attr, item_str_r_type_attr);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public static Dialog showDialog(int btnstyle, int thmeecolor, Context context, String title, int linecolor, List<String> liststring, AdapterView.OnItemClickListener onitemclicklistener, int str_r_type_attr, int item_str_r_type_attr) {
        final DialogUtil.DialogInfo du = new DialogUtil.DialogInfo(context);
        du.aty = context;
        Context ctx = context;
        du.view = LayoutInflater.from(ctx).inflate(str_r_type_attr, null);
        AdapterView listview = (AdapterView) du.view.findViewById(R.id.listview);
        //有歧义
        String big = "";
        if (liststring != null && liststring.size() > 0) {
            for (String s : liststring) {
                big += ",[" + s +
                        "]";
            }
        }
        if (!TextUtils.isEmpty(big) && big.length() > 1) {
            big = big.substring(1);
        }
        listview.setTag("fake:[" +
                big + "];layout:");
        MapViewConf.with(context).source(liststring
                , listview).conf(MapViewConf.with(context).source(item_str_r_type_attr == -1 ? R.layout.auto_string_item : item_str_r_type_attr)).toView();
        du.neutralButtonClickListener = new DialogUtil.DialogClicker();
        listview.setOnItemClickListener(onitemclicklistener);
        View header = du.view.findViewById(R.id.string);
        if (header != null && ((TextView) header.findViewById(R.id.name)) != null) {
            ((TextView) header.findViewById(R.id.name)).setTextColor(ctx.getColor(android.R.color.white));
            if (thmeecolor != -1) {
                header.setBackgroundColor(ctx.getColor(thmeecolor));
            }

            if (!TextUtils.isEmpty(title)) {
                ((TextView) header.findViewById(R.id.name)).setText(title);
            } else {
                ((ViewGroup) ((TextView) header.findViewById(R.id.name)).getParent()).setVisibility(View.GONE);
                ((TextView) header.findViewById(R.id.name)).setVisibility(View.GONE);
            }
        }
        if (dialog != null) {
            DialogUtil.cancelDialog();
        }
        if (btnstyle == BOTN) {

            du.positiveButtonText = "好的";
            du.negativeButtonText = "取消";
            dialog = DialogUtil.showChoiceDialog(du, true);

        } else if (btnstyle == Three) {

            du.positiveButtonText = "好的";
            du.negativeButtonText = "取消";
            du.neutralButtonText = "就这样";
            dialog = DialogUtil.showChoiceDialog(du, true);

        } else if (btnstyle == Neutral) {
            dialog = DialogUtil.getNeutralDialogBuilder(du, true).show();
        } else if (btnstyle == NONE) {
            dialog = DialogUtil.showChoiceDialog(du, true);
        }
        if (Build.VERSION.SDK_INT == 28) {
            api28_9_dialog_key_problem();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    api28_9_dialog_key_problem();

                }
            }, 2000);
        }
        if (dialog != null && !dialog.isShowing()) {
            dialog.show();
        }
        setCurrentDialog(dialog);
        return dialog;
    }

    public static void api28_9_dialog_key_problem() {
        try {
            if (dialog == null || !dialog.isShowing()) {
                return;
            }
            ViewParent viewRootImpl = dialog.getWindow().getDecorView().getParent();
            if (viewRootImpl == null) {
                return;
            }
            Class viewRootImplClass = viewRootImpl.getClass();

            Field mAttachInfoField = viewRootImplClass.getDeclaredField("mAttachInfo");
            mAttachInfoField.setAccessible(true);
            Object mAttachInfo = mAttachInfoField.get(viewRootImpl);
            Class mAttachInfoClass = mAttachInfo.getClass();

            Field mHasWindowFocusField = mAttachInfoClass.getDeclaredField("mHasWindowFocus");
            mHasWindowFocusField.setAccessible(true);
            mHasWindowFocusField.set(mAttachInfo, true);
            boolean mHasWindowFocus = (boolean) mHasWindowFocusField.get(mAttachInfo);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static Dialog showDialog(View view, View listview, DialogInterface.OnClickListener confirmlistener) {
        return showDialog(listview.getContext(), listview, confirmlistener);
    }

    public static Dialog showDialog(View listview, DialogInterface.OnClickListener confirmlistener) {
        return showDialog(listview.getContext(), listview, confirmlistener);
    }

    public static Dialog showDialog(Context ctx, View listview, DialogInterface.OnClickListener confirmlistener) {
        return showDialog(ctx, listview, "OK", confirmlistener);
    }

    public static Dialog showDialog(Context ctx, View listview, String neuBtnT, DialogInterface.OnClickListener confirmlistener) {
        return showDialog(ctx, listview, neuBtnT, confirmlistener, "", null, "", null);
    }

    public static Dialog showDialog(Context ctx, View listview, String neuBtnT, DialogInterface.OnClickListener confirmlistener, String posiBtnT, DialogInterface.OnClickListener posilistener, String negaBtnT, DialogInterface.OnClickListener negalisener) {
        DialogUtil.DialogInfo du = new DialogUtil.DialogInfo(ctx);
        du.aty = ctx;
//        ViewGroup.MarginLayoutParams mps = new ViewGroup.MarginLayoutParams(-1,-1);
//        mps.bottomMargin = 10;
//        mps.leftMargin = 10;
//        mps.rightMargin = 10;
//        mps.topMargin = 10;
//        listview.setLayoutParams(mps);
        du.view = listview;
        if (TextUtils.isEmpty(posiBtnT)) {
            du.positiveButtonText = "";
        } else {
            du.positiveButtonText = posiBtnT;
        }
        if (posilistener == null) {
            du.positiveButtonClickListener = new DialogUtil.DialogClicker();
        } else {
            du.positiveButtonClickListener = posilistener;
        }

        if (TextUtils.isEmpty(negaBtnT)) {
            du.negativeButtonText = "";
        } else {
            du.negativeButtonText = negaBtnT;
        }
        if (negalisener == null) {
            du.negativeButtonClickListener = new DialogUtil.DialogClicker();
        } else {
            du.negativeButtonClickListener = negalisener;
        }

        if (confirmlistener == null) {
            du.neutralButtonClickListener = new DialogUtil.DialogClicker();
            return DialogUtil.showChoiceDialog(du, true);
        } else {
//            du.negativeButtonClickListener = new DialogClicker() {
//                @Override
//                public void onClick(DialogInterface dialog, int arg1) {
//                    super.onClick(dialog, arg1);
//                    DialogUtil.cancelDialog();
//                }
//            };
            du.neutralButtonText = neuBtnT;
            du.neutralButtonClickListener = confirmlistener;
            Dialog d =
                    setCurrentDialog(DialogUtil.showChoiceDialog(du, true));
            d.getWindow().getDecorView().setBackgroundColor(Color.WHITE);
            return d;

        }
    }

    public static Dialog showChoiceDialog(Context ctx, View listview, String posi, DialogInterface.OnClickListener confirmlistener, String nega, DialogInterface.OnClickListener cancellistener) {
        DialogUtil.DialogInfo du = new DialogUtil.DialogInfo(ctx);
        du.aty = ctx;
//        ViewGroup.MarginLayoutParams mps = new ViewGroup.MarginLayoutParams(-1,-1);
//        mps.bottomMargin = 10;
//        mps.leftMargin = 10;
//        mps.rightMargin = 10;
//        mps.topMargin = 10;
//        listview.setLayoutParams(mps);
        du.view = listview;
        if (confirmlistener == null) {
            du.positiveButtonClickListener = new DialogUtil.DialogClicker();
        } else {
            du.positiveButtonText = posi;
            du.positiveButtonClickListener = confirmlistener;
        }
        if (cancellistener == null) {
            du.negativeButtonClickListener = new DialogUtil.DialogClicker();
        } else {
            du.negativeButtonText = nega;
            du.negativeButtonClickListener = cancellistener;
        }
        Dialog d =
                setCurrentDialog(DialogUtil.showChoiceDialog(du, true));
        d.getWindow().getDecorView().setBackgroundColor(Color.WHITE);
        return d;

    }

    public static Dialog setCurrentDialog(Dialog currentDialog) {
        DialogUtil.currentDialog = currentDialog;
        return currentDialog;
    }

    @Override
    public AndroidInstance use(Object mp, Object... p) {
        return null;
    }

    public static class DialogClicker implements
            DialogInterface.OnClickListener {

        public void onClick(DialogInterface dialog, int arg1) {
            dialog.cancel();
            dialog.dismiss();
        }

    }

    public static final int loading = 0;

    public static class DialogInfo {
        public String title;
        public int iconId;
        public SpannableStringBuilder message;
        public String positiveButtonText;
        public DialogInterface.OnClickListener positiveButtonClickListener;
        public String negativeButtonText;
        public DialogInterface.OnClickListener negativeButtonClickListener;
        public String neutralButtonText;
        public DialogInterface.OnClickListener neutralButtonClickListener;
        public View view;

        public Context aty;

        public DialogInfo(Context context) {
            super();
            this.aty = context;
        }

    }

    public static DialogInterface.OnClickListener getNewCancelOption(
            Context activity) {
        return getNewCancelOption(activity, false);
    }

    public static DialogInterface.OnClickListener getNewCancelOption(
            final Context activity, final boolean destroyActivity) {
        return new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                dialog.dismiss();

            }
        };
    }

    public static AlertDialog showChoiceDialog(DialogInfo abtract) {

        AlertDialog dialog = showChoiceDialog(abtract, true);
        return dialog;
    }

    public static AlertDialog showChoiceDialog(DialogInfo abtract,
                                               boolean cancelable) {
        if (abtract.aty == null) {
            throw new IllegalStateException("contxet is null");
        }
        Builder dialog = new Builder(abtract.aty)
                .setCancelable(cancelable);
        if (abtract.positiveButtonText != null
                && abtract.positiveButtonClickListener != null) {
            dialog.setPositiveButton(abtract.positiveButtonText,

                    abtract.positiveButtonClickListener);

        }
        if (abtract.negativeButtonText != null
                && abtract.negativeButtonClickListener != null) {
            dialog.setNegativeButton(abtract.negativeButtonText,
                    abtract.negativeButtonClickListener);

        }

        if (abtract.neutralButtonText != null
                && abtract.neutralButtonClickListener != null) {
            dialog.setNeutralButton(abtract.neutralButtonText,
                    abtract.neutralButtonClickListener);

        }


        if (abtract.title != null) {
            dialog.setTitle(abtract.title);
        }
        if (abtract.iconId != 0) {
            dialog.setIcon(abtract.iconId);
        }
        if (abtract.message != null) {
            dialog.setMessage(abtract.message);
        }
        if (abtract.view != null) {
            dialog.setView(abtract.view);
        }
        AlertDialog ad = dialog.create();
//        if (((Activity) ad.getContext()).isFinishing()) {
        try {
            ad.show();
//        }
        } catch (Exception e) {

        }
        return ad;
    }

    public static AlertDialog showNeutralDialog(DialogInfo abtract) {
        return showNeutralDialog(abtract, false);
    }

    public static AlertDialog showNeutralDialog(DialogInfo abtract,
                                                boolean cancable) {
        return new Builder(abtract.aty)
                .setTitle(abtract.title)
                .setIcon(abtract.iconId)
                .setMessage(abtract.message)
                .setNeutralButton(abtract.neutralButtonText,
                        abtract.neutralButtonClickListener)
                .setCancelable(cancable).setView(abtract.view).show();
    }


    public static AlertDialog.Builder getNeutralDialogBuilder(DialogInfo abtract,
                                                              boolean cancable) {
        return new Builder(abtract.aty)
                .setTitle(abtract.title)
                .setIcon(abtract.iconId)
                .setMessage(abtract.message)
                .setNeutralButton(abtract.neutralButtonText,
                        abtract.neutralButtonClickListener)
                .setCancelable(cancable).setView(abtract.view);
    }

    public void closeHintNBackToLauncher(DialogInterface dialog, Context context) {
        dialog.dismiss();
        dialog.cancel();
        ((Activity) context).finish();
    }
}
